package com.ruoyi.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.ruoyi.common.utils.http.HttpUtils;

/**
 * 微信HTTP请求工具类
 *
 * @author ruoyi
 */
public class WXHttpUtils {
    public static final String WX_CODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";    // 小程序登录接口

    public static final String WX_JS_API = "https://api.mch.weixin.qq.com//v3/pay/partner/transactions/jsapi";    // 微信支付接口

    public static final String WX_ORDER_QUERY_URL = "https://api.mch.weixin.qq.com/pay/orderquery";    // 订单查询接口

    public static final String WX_CLOSE_ORDER_URL = "https://api.mch.weixin.qq.com/pay/closeorder";    // 订单关闭接口

    public static final String WX_REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";    // 退款接口

    public static final String WX_REFUND_QUERY_URL = "https://api.mch.weixin.qq.com/pay/refundquery";    // 退款查询接口


    /**
     * 微信小程序登录，通过js_code获取session_key和openid
     * 调用API: https://api.weixin.qq.com/sns/jscode2session
     * 详情请见：
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     *
     * @param appid  小程序唯一标识
     * @param secret 小程序的app secret
     * @param jsCode 登录时获取的code
     * @return 响应结果，包含session_key和openid等信息
     */
    public static String jscode2session(String appid, String secret, String jsCode) {
        try {
            // 对参数进行URL编码，避免特殊字符导致请求错误
            String encodedAppid = URLEncoder.encode(appid, StandardCharsets.UTF_8.name());
            String encodedSecret = URLEncoder.encode(secret, StandardCharsets.UTF_8.name());
            String encodedJsCode = URLEncoder.encode(jsCode, StandardCharsets.UTF_8.name());

            // 构建请求参数
            String param = "appid=" + encodedAppid + "&secret=" + encodedSecret + "&js_code=" + encodedJsCode + "&grant_type=authorization_code";

            // 调用已有的HttpUtils发送GET请求
            return HttpUtils.sendGet(WX_CODE_TO_SESSION_URL, param);
        } catch (UnsupportedEncodingException e) {
            // UTF-8编码支持是标准的，此异常理论上不会发生
            throw new RuntimeException("编码异常", e);
        }
    }


    public static String sendJSAPIPost(String authorization, Map<String, Object> requestParams) {
        String response = "";
        try {
            // 构建请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", authorization);
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json");

            // 构建请求体（JSON格式示例）
            String body = "{\"sp_appid\":\"wx123\",\"sp_mchid\":\"123456\",\"amount\":{\"total\":100}}";

            // 发送请求
            response = HttpUtils.sendSSLPost(WXHttpUtils.WX_JS_API, headers, body);
        } catch (Exception e) {
            throw new RuntimeException("发送微信JSAPI支付请求失败", e);
        }
        return response;
    }
}
